package com.ehotting.edsta.circuitDesign.gen;

import com.alibaba.fastjson.JSON;
import com.ehotting.edsta.circuitDesign.exception.LoggerTar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.ScriptException;


public class ScriptLogger {


    public static void info(String msg){
        LoggerTar.scriptInfo.info(msg);
    }
    public static void info(String msg,String... args){
        LoggerTar.scriptInfo.info(msg,args);
    }

    public static void error(String msg){
        LoggerTar.scriptError.error(msg);
    }

    public static void error(Throwable e,String script,Object[] args){
        StringBuffer pathBuffer = new StringBuffer();

        if(e.getCause()!=null){
            e = e.getCause();
        }
        pathBuffer.append(e.getMessage()).append(ScriptConstants.LINE);
        StackTraceElement[] stackTraceElementArray = e.getStackTrace();
        for(StackTraceElement ste : stackTraceElementArray){
            if(ste!=null && ste.getFileName()!=null && ste.getFileName().contains(".groovy") || ste.getFileName().indexOf(".groovy")>=0) {
                pathBuffer.append(ste.getMethodName()).append("(line").append(ste.getLineNumber()).append(")").append(ScriptConstants.LINE);
            }
        }

        ErrorInfo errorInfo = new ErrorInfo(pathBuffer.toString(),script,args);
        ScriptLogger.error(errorInfo.toString());
    }

    public static class ErrorInfo{
        private String path;
        private String script;
        private Object[] args;

        public ErrorInfo() {
        }

        public ErrorInfo(String path, String script, Object[] args) {
            this.path = path;
            this.script = script;
            this.args = args;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getScript() {
            return script;
        }

        public void setScript(String script) {
            this.script = script;
        }

        public Object[] getArgs() {
            return args;
        }

        public void setArgs(Object[] args) {
            this.args = args;
        }

        public void log(){

        }

        @Override
        public String toString() {
            StringBuffer buf = new StringBuffer();
            buf.append("[PATH]").append(ScriptConstants.LINE).append(path).append(ScriptConstants.LINE);
            buf.append("[ARGS]").append(ScriptConstants.LINE).append(JSON.toJSONString(args)).append(ScriptConstants.LINE);
            buf.append("[SCRIPT]").append(ScriptConstants.LINE).append(script).append(ScriptConstants.LINE);
            return buf.toString();
        }
    }

}
